package com.cloud.pdd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.pdd.mapper.CjPddYangkeduoMapper;
import com.cloud.pdd.model.domain.CjPddDomain;
import com.cloud.sh.model.entity.CjPddYangkeduo;
import com.cloud.pdd.model.request.CjPddListRequest;
import com.cloud.pdd.service.CjPddYangkeduoService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 采集拼多多商品
 *
 * @author douhaichao code generator
 * @date 2021-03-18 20:59:14
 */
@Service
@AllArgsConstructor
public class CjPddYangkeduoServiceImpl extends ServiceImpl<CjPddYangkeduoMapper, CjPddYangkeduo> implements CjPddYangkeduoService {

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public CjPddYangkeduo selectOne(CjPddYangkeduo req) {
        QueryWrapper queryWrapper = new QueryWrapper<CjPddYangkeduo>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<CjPddYangkeduo> selectAll(CjPddYangkeduo req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<CjPddYangkeduo> selectPage(Page page, CjPddYangkeduo req) {
        IPage<CjPddYangkeduo> list = baseMapper.selectPage(
                page,
                new QueryWrapper<CjPddYangkeduo>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<CjPddYangkeduo> selectPageByLike(Page page, CjPddYangkeduo req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (!StrUtil.isEmpty(req.getTitle())) {
            queryWrapper.like("title", req.getTitle());
        }

        if (!StrUtil.isEmpty(req.getImages())) {
            queryWrapper.like("images", req.getImages());
        }

        if (null != req.getOriginalPrice()) {
            queryWrapper.eq("original_price", req.getOriginalPrice());
        }

        if (null != req.getCurrentPrice()) {
            queryWrapper.eq("current_price", req.getCurrentPrice());
        }

        if (!StrUtil.isEmpty(req.getSellerName())) {
            queryWrapper.like("seller_name", req.getSellerName());
        }

        if (!StrUtil.isEmpty(req.getContent())) {
            queryWrapper.like("content", req.getContent());
        }

        if (!StrUtil.isEmpty(req.getBrand())) {
            queryWrapper.like("brand", req.getBrand());
        }

        if (!StrUtil.isEmpty(req.getDrugName())) {
            queryWrapper.like("drug_name", req.getDrugName());
        }

        if (!StrUtil.isEmpty(req.getCommonDrugName())) {
            queryWrapper.like("common_drug_name", req.getCommonDrugName());
        }

        if (!StrUtil.isEmpty(req.getSpecifications())) {
            queryWrapper.like("specifications", req.getSpecifications());
        }

        if (!StrUtil.isEmpty(req.getDosage())) {
            queryWrapper.like("dosage", req.getDosage());
        }

        if (!StrUtil.isEmpty(req.getDose())) {
            queryWrapper.like("dose", req.getDose());
        }

        if (!StrUtil.isEmpty(req.getApprovalNumber())) {
            queryWrapper.like("approval_number", req.getApprovalNumber());
        }

        if (!StrUtil.isEmpty(req.getCategory())) {
            queryWrapper.like("category", req.getCategory());
        }

        if (!StrUtil.isEmpty(req.getValidity())) {
            queryWrapper.like("validity", req.getValidity());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (null != req.getIsDel()) {
            queryWrapper.eq("is_del", req.getIsDel());
        }

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }
        IPage<CjPddYangkeduo> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(CjPddYangkeduo req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public IPage<CjPddYangkeduo> selectCjPddList(Page page, CjPddListRequest req) {
        CjPddYangkeduo cjPddYangkeduo = new CjPddYangkeduo();
        BeanUtil.copyProperties(req, cjPddYangkeduo);
        QueryWrapper<CjPddYangkeduo> cjPddYangkeduoQueryWrapper = new QueryWrapper<CjPddYangkeduo>();

        cjPddYangkeduoQueryWrapper.select("id,title,images,create_time");
        cjPddYangkeduoQueryWrapper.lambda().eq(CjPddYangkeduo::getUserId, req.getUserId());
        if (!StrUtil.isEmpty(req.getTitle())) {
            cjPddYangkeduoQueryWrapper.lambda().like(CjPddYangkeduo::getTitle, req.getTitle());
        }
        if (!StrUtil.isEmpty(req.getStartTime())) {
            cjPddYangkeduoQueryWrapper.apply("create_time>='" + req.getStartTime() + "'");
        }
        if (!StrUtil.isEmpty(req.getEndTime())) {
            cjPddYangkeduoQueryWrapper.apply("create_time<date_add('" + req.getEndTime() + "',INTERVAL 1 DAY)");
        }
        cjPddYangkeduoQueryWrapper.orderByDesc("id");
        IPage<CjPddYangkeduo> list = baseMapper.selectPage(
                page, cjPddYangkeduoQueryWrapper
        );
        return list;
    }

    @Override
    public void cjPddData(CjPddYangkeduo req) {
        String content = req.getContent();
        content = ReUtil.getGroup1("window.rawData=([\\s\\S]+?)</script>", content);
        if (StrUtil.isEmpty(content)) {
            return;
        }
        content = StrUtil.trimEnd(content);
        content = content.substring(0, content.length() - 1);
        JSONObject jsonObject = JSONUtil.parseObj(content);
        rootNode(jsonObject, req.getUserId());
    }

    private void rootNode(JSONObject jsonObject, Integer userId) {
        //root 节点
        Object store = jsonObject.get("store");
        JSONObject jsonStore = JSONUtil.parseObj(store);
        initDataObjNode(jsonStore, userId);
    }

    private void initDataObjNode(JSONObject jsonStore, Integer userId) {
        String initDataObj = Convert.toStr(jsonStore.get("initDataObj"));
        JSONObject jsonGoods = JSONUtil.parseObj(initDataObj);
        goodsNode(jsonGoods, userId);
    }

    private void goodsNode(JSONObject jsonGoods, Integer userId) {

        CjPddYangkeduo cjPddYangkeduo = new CjPddYangkeduo();
        cjPddYangkeduo.setUserId(userId);
        //goods节点
        JSONObject jsonGoodsDetail = JSONUtil.parseObj(jsonGoods.get("goods"));
        //门店信息
        JSONObject jsonOakData = JSONUtil.parseObj(jsonGoods.get("oakData"));
        //认证门店名称 信息开始
        JSONObject ui = JSONUtil.parseObj(jsonOakData.get("ui"));
        JSONObject brandSection = JSONUtil.parseObj(ui.get("brandSection"));
        JSONObject blackBrand = JSONUtil.parseObj(brandSection.get("blackBrand"));
        String seller_name = Convert.toStr(blackBrand.get("brand"));
        cjPddYangkeduo.setSellerName(seller_name);
        //认证门店名称 信息结束
        //商品详情 信息开始
        JSONObject uiGoods = JSONUtil.parseObj(jsonOakData.get("goods"));
        List<CjPddDomain> listDecoration = JSONUtil.toList(Convert.toStr(uiGoods.get("decoration")), CjPddDomain.class);
        Set<String> setImage = new HashSet<>();
        for (CjPddDomain item : listDecoration) {
            String contents = item.getContents();
            List<CjPddDomain> listImgUrl = JSONUtil.toList(contents, CjPddDomain.class);
            Set<String> collect = listImgUrl.stream().map(t -> t.getImgUrl()).collect(Collectors.toSet());
            setImage.addAll(collect);
        }
        String content = StrUtil.join(",", setImage);
        cjPddYangkeduo.setContent(content);
        //商品详情 信息结束

        String goodsName = Convert.toStr(jsonGoodsDetail.get("goodsName"));
        cjPddYangkeduo.setTitle(goodsName);
        String images = getImages(jsonGoodsDetail);
        cjPddYangkeduo.setImages(images);
        //原价格
        String originalPrice = Convert.toStr(jsonGoodsDetail.get("linePrice"));
        cjPddYangkeduo.setOriginalPrice(Convert.toBigDecimal(originalPrice, BigDecimal.ZERO));
        //现价格
        String currentPrice = Convert.toStr(jsonGoodsDetail.get("minGroupPrice"));
        cjPddYangkeduo.setCurrentPrice(Convert.toBigDecimal(currentPrice, BigDecimal.ZERO));

        //属性开始
        String goodsProperty = StrUtil.toString(jsonGoodsDetail.get("goodsProperty"));
        List<CjPddDomain> listGoodsProperty = JSONUtil.toList(goodsProperty, CjPddDomain.class);
        CjPddDomain brandModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("品牌")).findFirst().orElse(new CjPddDomain());
        String brand = brandModel.getValues();
        cjPddYangkeduo.setBrand(brand);
        CjPddDomain drugNameModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("药品名称")).findFirst().orElse(new CjPddDomain());
        String drugName = drugNameModel.getValues();
        cjPddYangkeduo.setDrugName(drugName);
        CjPddDomain commonDrugNameModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("药品通用名")).findFirst().orElse(new CjPddDomain());
        String commonDrugName = commonDrugNameModel.getValues();
        cjPddYangkeduo.setCommonDrugName(commonDrugName);
        CjPddDomain specificationsModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("药品规格")).findFirst().orElse(new CjPddDomain());
        String specifications = specificationsModel.getValues();
        cjPddYangkeduo.setSpecifications(specifications);
        CjPddDomain dosageModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("产品剂型")).findFirst().orElse(new CjPddDomain());
        String dosage = dosageModel.getValues();
        cjPddYangkeduo.setDosage(dosage);
        CjPddDomain doseModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("使用剂量")).findFirst().orElse(new CjPddDomain());
        String dose = doseModel.getValues();
        cjPddYangkeduo.setDose(dose);
        CjPddDomain approvalNumberModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("批准文号")).findFirst().orElse(new CjPddDomain());
        String approvalNumber = approvalNumberModel.getValues();
        cjPddYangkeduo.setApprovalNumber(approvalNumber);
        CjPddDomain categoryModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("药品分类")).findFirst().orElse(new CjPddDomain());
        String category = categoryModel.getValues();
        cjPddYangkeduo.setCategory(category);
        CjPddDomain validityModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("有效期")).findFirst().orElse(new CjPddDomain());
        String validity = validityModel.getValues();
        cjPddYangkeduo.setValidity(validity);
        CjPddDomain leibieModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("药品类别")).findFirst().orElse(new CjPddDomain());
        String leibie = leibieModel.getValues();
        cjPddYangkeduo.setLeibie(leibie);
        CjPddDomain shengchangqiyeModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("生产企业")).findFirst().orElse(new CjPddDomain());
        String shengchangqiye = shengchangqiyeModel.getValues();
        cjPddYangkeduo.setShengchangqiye(shengchangqiye);
        CjPddDomain yongfaModel = listGoodsProperty.stream().filter(t -> t.getKey().equals("用法")).findFirst().orElse(new CjPddDomain());
        String yongfa = yongfaModel.getValues();
        cjPddYangkeduo.setYongfa(yongfa);
        //属性结束
        baseMapper.insert(cjPddYangkeduo);
    }

    private String getImages(JSONObject jsonGoods) {
        String topGallery = StrUtil.toString(jsonGoods.get("topGallery"));
        List<CjPddDomain> list = JSONUtil.toList(topGallery, CjPddDomain.class);
        Set<String> collect = list.stream().map(t -> t.getUrl()).collect(Collectors.toSet());
        return StrUtil.join(",", collect);
    }

}
